package mammuthus.web.action

import java.net.URLEncoder
import scala.collection.JavaConversions._
import javax.servlet.http.HttpServletRequest
import mammuthus.web.bean.{Task, TaskInfo, SlaveBean, ShellResult}
import net.sf.json.{JSONObject, JSONArray}
import net.liftweb.{json => SJSon}
import java.util

/**
 * 5/26/15 WilliamZhu(allwefantasy@gmail.com)
 */
trait ActionHelperTrait {
  /*
    将  req.getParameterMap 获取到的参数组装成Url参数，并且进行编码
   */
  def encodeFromMapToUrlQuery(params: java.util.Map[_, _]) = {
    val abc = params.entrySet().map {
      f => (f.getKey.asInstanceOf[String], f.getValue.asInstanceOf[Array[String]])
    }
    abc.map {
      f => s"${f._1}=${URLEncoder.encode(f._2.mkString(","), "utf-8")}"
    }.mkString("&")
  }

  def putToReqAttribute(req: HttpServletRequest, params: java.util.Map[_, _]) = {
    val abc = params.entrySet().map {
      f => (f.getKey.asInstanceOf[String], f.getValue.asInstanceOf[Array[String]])
    }
    val res = abc.map(f => (f._1, f._2.mkString(","))).toMap
    val paramsForReq: java.util.Map[String, String] = res
    req.setAttribute("params", paramsForReq)
    res
  }

  def putToReqAttribute(req: HttpServletRequest) = {
    val abc = req.getParameterMap.entrySet().map {
      f => (f.getKey.asInstanceOf[String], f.getValue.asInstanceOf[Array[String]])
    }
    val res = abc.map(f => (f._1, f._2.mkString(","))).toMap
    val paramsForReq: java.util.Map[String, String] = res
    req.setAttribute("params", paramsForReq)
    res
  }

  def nav(req: HttpServletRequest, shellResult: ShellResult, prePath: (String, String), nextPath: (String, String), enableAll: Boolean = false) = {
    val np = if (nextPath._2 == "-") "" else s"""下一步:<a  class="btn"  href="${nextPath._1}">${nextPath._2}</a>"""
    val pp = if (prePath._2 == "-") "" else s"""上一步:<a class="btn" href="${prePath._1}">${prePath._2}</a>"""

    if (!shellResult.success) {
      req.setAttribute("tasks", new JSONArray())
      req.setAttribute("msg", s"""${shellResult.mgs} ${if (enableAll) pp + " " + np else pp}""")
    } else {
      req.setAttribute("shellRes", shellResult.tasks)
      req.setAttribute("tasks", toJava2(shellResult.taskInfos))
      req.setAttribute("msg", s""" ${if (enableAll) pp + " " + np else np} """)
    }
  }

  def nav(req: HttpServletRequest, shellResult: List[Map[String, AnyRef]], nextPath: (String, String)) = {
    val np = if (nextPath._2 == "-") "" else s"""下一步: <a  class="btn"  href="${nextPath._1}">${nextPath._2}</a>"""
    req.setAttribute("srs", toJavaList(shellResult))
    req.setAttribute("msg", s"${np}")
  }

  def nav2(req: HttpServletRequest, params: Map[String, String], shellResult: ShellResult, prePath: (String, String), nextPath: (String, String), enableAll: Boolean = false) = {
    val _prePath = (params.getOrElse("preUrl", prePath._1), params.getOrElse("prePath", prePath._2))
    val _nextPath = (params.getOrElse("nextUrl", nextPath._1), params.getOrElse("nextPath", nextPath._2))
    nav(req, shellResult, _prePath, _nextPath, enableAll)
  }

  def formatIP(slaves: util.List[SlaveBean]) = {
    implicit val formats = SJSon.DefaultFormats
    import scala.collection.JavaConversions._
    val temp: util.List[SlaveBean] = slaves.map {
      f =>
        f.ip = SJSon.parse(f.ip).extract[List[Eth]].map(f => f.ipv4).filter(f => f.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")).filterNot(f => f.startsWith("127.0")).mkString(",")
        f
    }
    temp
  }

  def fetchIp(slave: SlaveBean) = {
    implicit val formats = SJSon.DefaultFormats
    SJSon.parse(slave.ip).extract[List[Eth]].map(f => f.ipv4).filter(f => f.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")).filterNot(f => f.startsWith("127.0")).mkString(",")
  }

  def toJava2(tasks: List[TaskInfo]) = {
    implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)
    JSONArray.fromObject(SJSon.Serialization.write(tasks))
  }

  def toJavaMap(item: AnyRef) = {
    implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)
    JSONObject.fromObject(SJSon.Serialization.write(item))
  }

  def toJavaList(item: AnyRef) = {
    implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)
    JSONArray.fromObject(SJSon.Serialization.write(item))
  }

  def taskExtract(shellRes: String) = {
    implicit val formats = SJSon.DefaultFormats
    SJSon.parse(shellRes).extract[List[Task]]
  }

  def encode(para: String) = {
    URLEncoder.encode(para, "utf-8")
  }

}

case class Eth(name: String, ipv4: String, ipv6: String)
